package com.ma.springframework.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import com.ma.springframework.beans.BeansException;
import com.ma.springframework.beans.factory.DisposableBean;
import com.ma.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Method;

public class DisposableBeanAdapter implements DisposableBean {
    private final Object bean;
    private final String beanName;
    private String destoryMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition destoryMethodName) {
        this.bean = bean;
        this.beanName = beanName;
        this.destoryMethodName = destoryMethodName.getDestroyMethodName();
    }

    @Override
    public void destroy() throws Exception {
        //实现接口DisposableBean
        if (bean instanceof DisposableBean){
            ((DisposableBean) bean).destroy();
        }
        //配置信息destory-method
        if (StrUtil.isNotEmpty(destoryMethodName)&&!(bean instanceof DisposableBean && "destory".equals(this.destoryMethodName))){
            Method destoryMethod = bean.getClass().getMethod(destoryMethodName);
            if (null == destoryMethod){
                throw new BeansException("Could find a destory method named"+destoryMethodName+" on bean with name"+beanName);
            }
            destoryMethod.invoke(bean);
        }
    }
}
